package bot.controller;

import bot.mapper.RussianturntableMapper;
import bot.pojo.Russianturntable;
import bot.pojo.RussianturntableExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/russianturntable")
public class RussianTurntables {
   private RussianturntableExample russianturntableExampler = new RussianturntableExample();
   @Autowired
   private RussianturntableMapper russianturntableMapper;
   static Timer timer = new Timer();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date beforeD ;
   //创建一局转盘游戏
    @PostMapping("/createrussianturntable")//
    public String createrussianturntable(Russianturntable russianTurntable) throws ParseException {
        russianturntableExampler.clear();
        russianturntableExampler.createCriteria().andGroupIdEqualTo(russianTurntable.getGroupId());
        List<Russianturntable> russianturntablesList = russianturntableMapper.selectByExample(russianturntableExampler);
        //创建对局的群如果在数据库有就更新，否则创建
        StringBuffer buffer = new StringBuffer();
        Random myRandom = new Random();
        int[] luckNums = new int[russianTurntable.getAmmunitionLoaded()];
        for(int i=0; i<russianTurntable.getAmmunitionLoaded(); i++) {
            //在1到44之间取随机数
            int randomNum = myRandom.nextInt(6) + 1;
            while(existed(randomNum, luckNums, i)) {
                randomNum = myRandom.nextInt(6) + 1;
            }
            luckNums[i] = randomNum;
        }
        Arrays.sort(luckNums);
        buffer.append(luckNums[0]);
        if(russianturntablesList.size() == 0){
            Calendar beforeTime = Calendar.getInstance();
            beforeTime.add(Calendar.MINUTE, + 3);
            beforeD = beforeTime.getTime();
            System.out.println("往后推"+3+"分钟时间："+sdf.format(beforeD) );

            russianTurntable.setStatuss(0);
            russianTurntable.setAllFire(6);
            russianTurntable.setFireNumber(0);
            russianTurntable.setDeadNumber(buffer.toString());
            russianTurntable.setFirstfire(russianTurntable.getSponsor());
            russianTurntable.setOutTime(sdf.format(beforeD));
            russianturntableMapper.insert(russianTurntable);
            Date date = sdf.parse(sdf.format(beforeD));
            TimeOutEnd(russianTurntable.getId(),date);
        }
        else if(russianturntablesList.size() != 0){
            return "当前群有游戏正在进行";
        }
        return "对局创建完成，发送 !加入对局 可以加入游戏(三分钟无人接收自动关闭) ";
    }
    //创建后若3分钟无人接收自动取消
    public void TimeOutEnd (Integer id,Date time){
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                russianturntableMapper.deleteByPrimaryKey(id);
                System.out.println("定时器执行");
            }
        };
        timer.schedule(timerTask, time);
    }
    /**+++++++
     * 检验新生成的随机数是否已经存在
     * @param num 新产生的随机数
     * @param luckNums 当前随机数数组
     * @param index 当前随机数的索引
     * @return boolean 是否存在，存在则返回true，不存在则返回false
     */
    public static boolean existed(int num, int[] luckNums, int index) {
        for(int i=0; i<index; i++) {
            if(num == luckNums[i]) {
                return true;
            }
            //这个地方还可以增加一些处理，用来筛选不想要参加抽座位的同学学号
        }
        return false;
    }

    @GetMapping("/joinrussianturntable")
    public String joinrussianturntable(String groupid , String recipient) throws ParseException {
        russianturntableExampler.clear();
        russianturntableExampler.createCriteria().andGroupIdEqualTo(groupid).andStatussEqualTo(0);
        List<Russianturntable> russianturntablesList = russianturntableMapper.selectByExample(russianturntableExampler);
        if(russianturntablesList.size() == 0){
            return "false";
        }
        if(russianturntablesList.get(0).getSponsor().equals(recipient)){
            return "joinerror";
        }
        russianturntablesList.get(0).setRecipient(recipient);
        russianturntablesList.get(0).setStatuss(1);
        russianturntableMapper.updateByPrimaryKey(russianturntablesList.get(0));
        //当接收转盘后要去清空定时任务重新创建
        Cleartimer();
        return russianturntablesList.get(0).getFirstfire();
    }

    public void Cleartimer() throws ParseException {
        timer.cancel();
        timer = new Timer();
        russianturntableExampler.clear();
        russianturntableExampler.createCriteria().andStatussEqualTo(0);
        List<Russianturntable> russianturntablesList = russianturntableMapper.selectByExample(russianturntableExampler);
        if (russianturntablesList.size() == 0){

        }else{
            for(int i = 0 ; i < russianturntablesList.size() ; i ++){
                Date date = sdf.parse(russianturntablesList.get(i).getOutTime());
                TimeOutEnd(russianturntablesList.get(i).getId() ,date);
            }
        }

    }
    //开枪
    @GetMapping("/fire")
    public String fire(String groupid ,String userid){
        russianturntableExampler.clear();
        russianturntableExampler.createCriteria().andGroupIdEqualTo(groupid).andFirstfireEqualTo(userid);
        List<Russianturntable> russianturntables = russianturntableMapper.selectByExample(russianturntableExampler);
        if(russianturntables.size() == 0){
            return "你未加入游戏对局或不是你的回合";
        }else{
            Integer fireNumber = russianturntables.get(0).getFireNumber() + 1;
            if(fireNumber.toString().equals(russianturntables.get(0).getDeadNumber())){
                //开枪者死了
                if(russianturntables.get(0).getRecipient().equals(userid)){
                    russianturntableMapper.deleteByPrimaryKey(russianturntables.get(0).getId());
                    return "dead:" + russianturntables.get(0).getSponsor();
                }
                if(russianturntables.get(0).getSponsor().equals(userid)){
                    russianturntableMapper.deleteByPrimaryKey(russianturntables.get(0).getId());
                    return "dead:" + russianturntables.get(0).getRecipient();
                }
            }
            //没死
            else {
                if(russianturntables.get(0).getRecipient().equals(userid)){
                    russianturntables.get(0).setFirstfire(russianturntables.get(0).getSponsor());
                    russianturntables.get(0).setFireNumber(fireNumber);
                    russianturntableMapper.updateByPrimaryKey(russianturntables.get(0));
                    return "alie:" + russianturntables.get(0).getFirstfire();
                }
                if(russianturntables.get(0).getSponsor().equals(userid)){
                    russianturntables.get(0).setFirstfire(russianturntables.get(0).getRecipient());
                    russianturntables.get(0).setFireNumber(fireNumber);
                    russianturntableMapper.updateByPrimaryKey(russianturntables.get(0));
                    return "alie:" + russianturntables.get(0).getFirstfire();
                }
            }
        }
        return null;
    }
}

